import { Form, message, Input, Button } from 'antd';
import React, { useRef, useState, useCallback, useEffect } from 'react';
import axios from '../../axios';
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import { history, useModel } from 'umi';

import Captcha from 'react-captcha-code';
const Account: React.FC = () => {
  //全局提示
  const success = () => {
    message.success('This is a success message');
  };
  //声明表单
  const [loginForm] = Form.useForm();
  //声明表单数据
  const [formData, setFormData] = useState({});
  //登录处理函数

  const loginHandle = async (values: any) => {
    //获取表单数据
    // setFormData({ ...values })
    //表单验证
    //发送请求
    //登录成功
    const {
      data: { data, code, msg },
    } = await axios.post('login', { ...values });
    if (code === 200) {
      message.success(msg);
      //保存用户信息
      localStorage.setItem('userInfo', data.role._id);
      localStorage.setItem('userId', data._id);
      localStorage.setItem('username', data.username);
      history.push('/home/index', { data: data.role._id, name: data.username });
    } else {
      message.error(msg);
    }
  };
  //定义一个自定义控件
  //获取验证码
  const [verifyCode, setCode] = useState('');
  const handleClick = useCallback((captcha) => {}, []);
  useEffect(() => {
    setCode(verifyCode);
  }, [verifyCode]);
  const MyInput = (props: any) => {
    return (
      <span style={{ display: 'flex' }}>
        <Input
          {...props}
          placeholder="请输入右侧验证码"
          prefix={<MailOutlined />}
          style={{ width: '60%' }}
        />
        <div>
          <Captcha charNum={4} className="code" />
        </div>
      </span>
    );
  };
  const [passwordVisible, setPasswordVisible] = useState(false);
  return (
    <Form
      layout="horizontal"
      initialValues={{ size: 'large' }}
      size="large"
      name="loginForm"
      form={loginForm}
      onFinish={loginHandle}
      onValuesChange={(values) => {}}
    >
      <Form.Item name="username">
        <Input placeholder="请输入用户名" prefix={<UserOutlined />} />
      </Form.Item>
      <Form.Item name="password">
        <Input.Password
          placeholder="请输入登录密码"
          visibilityToggle={{
            visible: passwordVisible,
            onVisibleChange: setPasswordVisible,
          }}
          prefix={<LockOutlined />}
        />
      </Form.Item>
      <Form.Item name="verifyCode">
        <MyInput></MyInput>
      </Form.Item>
      <Form.Item>
        <Button
          type="primary"
          style={{ borderRadius: '10px', width: '100%' }}
          htmlType="submit"
        >
          登录
        </Button>
      </Form.Item>
    </Form>
  );
};

export default Account;
